"""
邮件模板相关的Pydantic模式定义
"""

from pydantic import BaseModel, validator
from typing import Optional, List, Dict, Any
from datetime import datetime
from enum import Enum


class TemplateType(str, Enum):
    """模板类型枚举"""
    HTML = "html"
    MARKDOWN = "markdown"
    PLAIN_TEXT = "plain_text"


class TemplateCategory(str, Enum):
    """模板分类枚举"""
    MARKETING = "marketing"      # 营销邮件
    NOTIFICATION = "notification"  # 通知邮件
    NEWSLETTER = "newsletter"    # 新闻邮件
    WELCOME = "welcome"         # 欢迎邮件
    REMINDER = "reminder"       # 提醒邮件
    CUSTOM = "custom"          # 自定义


class EmailTemplateCreate(BaseModel):
    """创建邮件模板请求模式"""
    name: str
    subject: str
    content: str
    template_type: TemplateType = TemplateType.HTML
    category: TemplateCategory = TemplateCategory.CUSTOM
    description: Optional[str] = None
    variables: Optional[List[str]] = []  # 模板变量列表
    is_active: bool = True
    
    @validator('name')
    def validate_name(cls, v):
        if not v or len(v.strip()) < 2:
            raise ValueError('模板名称至少需要2个字符')
        return v.strip()
    
    @validator('subject')
    def validate_subject(cls, v):
        if not v or len(v.strip()) < 1:
            raise ValueError('邮件主题不能为空')
        return v.strip()
    
    @validator('content')
    def validate_content(cls, v):
        if not v or len(v.strip()) < 1:
            raise ValueError('邮件内容不能为空')
        return v.strip()
    
    @validator('variables')
    def validate_variables(cls, v):
        if v is None:
            return []
        # 验证变量名格式
        for var in v:
            if not var or not var.replace('_', '').replace('-', '').isalnum():
                raise ValueError(f'变量名格式不正确: {var}')
        return list(set(v))  # 去重


class EmailTemplateUpdate(BaseModel):
    """更新邮件模板请求模式"""
    name: Optional[str] = None
    subject: Optional[str] = None
    content: Optional[str] = None
    template_type: Optional[TemplateType] = None
    category: Optional[TemplateCategory] = None
    description: Optional[str] = None
    variables: Optional[List[str]] = None
    is_active: Optional[bool] = None
    
    @validator('name')
    def validate_name(cls, v):
        if v is not None and (not v or len(v.strip()) < 2):
            raise ValueError('模板名称至少需要2个字符')
        return v.strip() if v else v
    
    @validator('subject')
    def validate_subject(cls, v):
        if v is not None and (not v or len(v.strip()) < 1):
            raise ValueError('邮件主题不能为空')
        return v.strip() if v else v
    
    @validator('content')
    def validate_content(cls, v):
        if v is not None and (not v or len(v.strip()) < 1):
            raise ValueError('邮件内容不能为空')
        return v.strip() if v else v
    
    @validator('variables')
    def validate_variables(cls, v):
        if v is None:
            return v
        # 验证变量名格式
        for var in v:
            if not var or not var.replace('_', '').replace('-', '').isalnum():
                raise ValueError(f'变量名格式不正确: {var}')
        return list(set(v))  # 去重


class EmailTemplateResponse(BaseModel):
    """邮件模板响应模式"""
    id: int
    name: str
    subject: str
    content: str
    template_type: TemplateType
    category: TemplateCategory
    description: Optional[str]
    variables: List[str]
    is_active: bool
    user_id: int
    created_at: datetime
    updated_at: datetime
    
    class Config:
        from_attributes = True


class EmailTemplateList(BaseModel):
    """邮件模板列表响应模式"""
    items: List[EmailTemplateResponse]
    total: int
    page: int
    size: int
    pages: int


class TemplatePreviewRequest(BaseModel):
    """模板预览请求模式"""
    template_id: Optional[int] = None
    subject: Optional[str] = None
    content: Optional[str] = None
    template_type: TemplateType = TemplateType.HTML
    variables: Optional[Dict[str, Any]] = {}
    
    @validator('variables')
    def validate_variables(cls, v):
        if v is None:
            return {}
        return v


class TemplatePreviewResponse(BaseModel):
    """模板预览响应模式"""
    rendered_subject: str
    rendered_content: str
    html_content: str  # 渲染后的HTML内容
    variables_used: List[str]
    missing_variables: List[str]


class TemplateVariableExtractRequest(BaseModel):
    """模板变量提取请求模式"""
    content: str
    subject: Optional[str] = None
    
    @validator('content')
    def validate_content(cls, v):
        if not v or len(v.strip()) < 1:
            raise ValueError('内容不能为空')
        return v.strip()


class TemplateVariableExtractResponse(BaseModel):
    """模板变量提取响应模式"""
    variables: List[str]
    subject_variables: List[str]
    content_variables: List[str]


class TemplateStatistics(BaseModel):
    """模板统计信息"""
    total: int
    active: int
    by_category: Dict[str, int]
    by_type: Dict[str, int]
    recent_added: int  # 最近7天新增


class TemplateCloneRequest(BaseModel):
    """模板克隆请求模式"""
    template_id: int
    new_name: str
    
    @validator('new_name')
    def validate_new_name(cls, v):
        if not v or len(v.strip()) < 2:
            raise ValueError('新模板名称至少需要2个字符')
        return v.strip()
